package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.entity.Dept;
import com.bnz.entity.R;
import com.bnz.service.DeptService;
import com.bnz.service.impl.DeptServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/dept")
public class DeptServlet extends HttpServlet {
    private DeptService deptService;

    @Override
    public void init() throws ServletException {
        deptService = new DeptServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置相应内容及字符集编码，将查询的内容送到前端页面上
        resp.setContentType("text/html;charset=utf8");
        // 2. 查询所有部门列表
        List<Dept> dept = deptService.findAll();
        // 3. 将dept对象转换为R对象
        R r = R.ok().put("list", dept);
        // 4. 将R对象转换为JSON对象
        String s = JSON.toJSONString(r);
        // 5. 输出
        resp.getWriter().println(s);
        // 6. 刷新
        resp.getWriter().flush();
    }
}
